package com.sell.service.impl;

import com.sell.dto.OrderDTO;
import com.sell.enums.SellExceptionEnum;
import com.sell.exception.SellException;
import com.sell.service.BuyerService;
import com.sell.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: lichujun
 * @date: 2018-08-17
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {
    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return checkOwner(openid, orderId);
    }

    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {
        OrderDTO orderDTO = checkOwner(openid, orderId);
        if (orderDTO == null) {
            log.error("【取消订单】订单不存在，openid={}，orderId={}", openid, orderId);
            throw new SellException(SellExceptionEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    private OrderDTO checkOwner(String openid, String orderId) {
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            return null;
        }
        //判断是否本人订单
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
            log.error("【查询订单】订单openid不一致，openid={}，orderDTO={}", openid, orderDTO);
            throw new SellException(SellExceptionEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
